package com.zhongde.cloud89app.activity;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.tu.loadingdialog.LoadingDailog;
import com.zhongde.cloud89app.R;
import com.zhongde.cloud89app.utils.MyPreference;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigInteger;

import okhttp3.Call;
import okhttp3.Request;

import static com.zhongde.cloud89app.base.Configuration.BASE_URL;

public class SetActivity extends AppCompatActivity {
    //抄表方式                       //使用区域
    private Spinner spinner_cbfs, spinner_syqy;
    private TextView tips;
    private EditText ed_zddzm, ed_xzqhm, ed_zddz16, ed_ljdz;
    private String menuname;
    private LinearLayout view_zddz, view_xzqhm, view_ljdzm, view_zddz16;
    private Button sub;
    private Button sub_delet;
    private MyPreference pref;
    private LoadingDailog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set);
        initView();
    }

    private void initView() {
        LoadingDailog.Builder loadBuilder = new LoadingDailog.Builder(this)
                .setMessage("登录中...")
                .setCancelable(false)
                .setCancelOutside(false);
        dialog = loadBuilder.create();
        pref = new MyPreference(this);
        menuname = getIntent().getStringExtra("menuname");
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("设置" + menuname);

        sub_delet = findViewById(R.id.sub_delet);
        view_zddz = findViewById(R.id.view_zddz);
        view_xzqhm = findViewById(R.id.view_xzqhm);
        view_ljdzm = findViewById(R.id.view_ljdz);

        ed_zddzm = findViewById(R.id.ed_zddzm);
        ed_xzqhm = findViewById(R.id.ed_xzqhm);
        ed_zddz16 = findViewById(R.id.ed_zddzm16);
        ed_ljdz = findViewById(R.id.ed_ljdz);

        view_zddz16 = findViewById(R.id.view_zddzm16);
        sub = findViewById(R.id.sub_set);
        spinner_cbfs = findViewById(R.id.spinner_cbfs);
        spinner_syqy = findViewById(R.id.spinner_syqy);
        tips = findViewById(R.id.tips);
        spinner_cbfs.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        spinner_syqy.setEnabled(true);
                        view_zddz.setVisibility(View.GONE);
                        view_xzqhm.setVisibility(View.GONE);
                        view_ljdzm.setVisibility(View.GONE);
                        view_zddz16.setVisibility(View.GONE);
                        tips.setText("路由载波：\n" +
                                "\n" +
                                "使用与台区集中器型号相同的路由载波模块");
                        break;
                    case 1:

                        spinner_syqy.setSelection(0);
                        spinner_syqy.setEnabled(false);
                        view_zddz.setVisibility(View.GONE);
                        view_xzqhm.setVisibility(View.GONE);
                        view_ljdzm.setVisibility(View.GONE);
                        view_zddz16.setVisibility(View.GONE);
                        tips.setText("路由载波：\n" +
                                "\n" +
                                "选择与台区集中器使用的相同型号载波模块，“使用区域”必须选择国家电网。");
                        break;
                    case 2:
                        spinner_syqy.setEnabled(true);
                        view_zddz.setVisibility(View.GONE);
                        view_xzqhm.setVisibility(View.GONE);
                        view_ljdzm.setVisibility(View.VISIBLE);
                        view_zddz16.setVisibility(View.GONE);

                        tips.setText("面向对象集中器：\n" +
                                "\n" +
                                "“使用区域”必须选择国家电网，“逻辑地址”输入集中器显示界面中的逻辑地址");
                        break;
                    case 3:
                        spinner_syqy.setEnabled(true);
                        view_zddz.setVisibility(View.VISIBLE);
                        view_xzqhm.setVisibility(View.VISIBLE);
                        view_zddz16.setVisibility(View.VISIBLE);
                        view_ljdzm.setVisibility(View.GONE);
                        tips.setText("RS-232：\n" +
                                "\n" +
                                "行政区码输入方式：输入集中器显示界面中的行政区码，共4位\n" +
                                "\n" +
                                "终端地址输入方式：输入集中器显示界面中的终端地址。选择其中一种方式输入即可。");

                        break;
                    case 4:
                        spinner_syqy.setEnabled(true);
                        view_zddz.setVisibility(View.GONE);
                        view_xzqhm.setVisibility(View.GONE);
                        view_ljdzm.setVisibility(View.GONE);
                        view_zddz16.setVisibility(View.GONE);
                        tips.setText("RS-485：\n" +
                                "\n" +
                                "目前只支持国网山东省RS-485方式抄表");

                        break;
                    default:

                        break;

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });


        sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sub();
            }
        });

        sub_delet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AlertDialog.Builder builder = new AlertDialog.Builder(SetActivity.this);
                builder.setTitle("警告");        //设置弹出窗口的标题
                builder.setMessage("是否确定解除设备绑定？");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    //设定PositiveButton
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        removeEquipment();
                    }
                });
                builder.setNeutralButton("取消", null);
                builder.show();


            }
        });

        ed_zddzm.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (ed_zddzm.getText().toString().isEmpty()) {
                        ed_zddz16.setText("");
                    } else {
                        ed_zddz16.setText(Integer.toHexString(Integer.parseInt(ed_zddzm.getText().toString().trim())));
                    }
                }


            }
        });

        ed_zddz16.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (ed_zddz16.getText().toString().isEmpty()) {
                        ed_zddzm.setText("");
                    } else {
                        BigInteger bigint = new BigInteger(ed_zddz16.getText().toString(), 16);
                        int numb = bigint.intValue();
                        ed_zddzm.setText(numb + "");

                    }

                }


            }
        });


    }

    private void sub() {

        String zddz = ed_zddzm.getText().toString().trim();
        String xzqhm = ed_xzqhm.getText().toString().trim();
        String ljdz = ed_ljdz.getText().toString().trim();
        String zddz16 = ed_zddz16.getText().toString().trim();
        int cbfs = 0;
        switch (spinner_cbfs.getSelectedItemPosition()) {

            case 0:
                cbfs = 1;
                break;
            case 1:
                cbfs = 6;
                break;

            case 2:
                cbfs = 3;
                if (ljdz.isEmpty()) {
                    Toast.makeText(SetActivity.this, "请输入逻辑地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                break;
            case 3:
                cbfs = 4;
                if (zddz.isEmpty()) {
                    Toast.makeText(SetActivity.this, "请输入终端地址", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (xzqhm.isEmpty()) {
                    Toast.makeText(SetActivity.this, "请输入行政区划码", Toast.LENGTH_SHORT).show();
                    return;
                }
                break;

            case 4:
                cbfs = 5;
                break;
        }

        OkHttpUtils
                .post()
                .url(BASE_URL + "A_Data_frame_sending_Controller/Judge_And_Set_Meter_Reading_Mode.do")
                .addParams("menuname", menuname)
                .addParams("connection", cbfs + "")
                .addParams("UseArea", (spinner_syqy.getSelectedItemPosition() + 1) + "")
                .addParams("AdministrativeAreaCode", xzqhm)
                .addParams("DecimalTerminalAddress", zddz)
                .addParams("TerminalAddress", ljdz)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(Request request, int id) {
                        super.onBefore(request, id);
                        dialog.show();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(SetActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Toast.makeText(SetActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onAfter(int id) {
                        super.onAfter(id);
                        dialog.dismiss();
                    }
                });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;

            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void removeEquipment() {
        OkHttpUtils
                .post()
                .url(BASE_URL + "Z_d_menuname_msg_Controller/deleteMenuname.do")
                .addParams("username", pref.getString("userName"))
                .addParams("menuname", menuname)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(SetActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Toast.makeText(SetActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                            if (jsonObject.getInt("code") == 1) {
                                finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}